<html>
<body>
<h1>Simple Calculator</h1>
<p>Type in expressions into the text field and click button to get answer.</p>
<form action="calculator.php" method="get">
Expression: <input type="text" name="expr" size="50" />
<br />
<br />
<input type="submit" value="Calculate" />
</form>
<?php
// get expression
if($expr = $_GET["expr"]) {
	// define tokens
	$number = '-?[0-9]+(\.[0-9]+)?';
	$operator = '[\+\-\*\/]';
	// pattern that matches a valid expression
	preg_match('/-?[0-9]+(\.[0-9]+)?([\+\-\*\/]{1}-?[0-9]+(\.[0-9]+)?)*/x', $expr, $matches);
	if ($expr == $matches[0]) {
		// handle divide by zero problem
		preg_match('/.*?\/0([^0-9].*)*/', $expr, $dvz);
		if ($expr == $dvz[0])
			echo "Divide by Zero problem. Please try again";
		// evaluate the expression
		else {
			eval("\$ans = $expr;");
			echo $expr." = ".$ans;
		}
	}
	else echo "Not valid expression. Please try again.";
}
?>
</form>
</body>
</html>